package com.sultan.guante.userSystem.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;





import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.sultan.guante.userSystem.dao.UserDAO;
import com.sultan.guante.userSystem.domain.Role;
import com.sultan.guante.userSystem.domain.Users;
import com.sultan.guante.userSystem.security.UserGrantedAuthority;
import com.sultan.guante.userSystem.service.SecurityService;



	@Component("securityService")
	public class SecurityServiceImpl implements SecurityService, Serializable {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;


		@Autowired
		private UserDAO userDao;
		
		
		@Autowired
		@Qualifier("authenticationManager")
		private AuthenticationManager authenticationManager;
		
		
		@Override
		@Transactional
		public UserDetails loadUserByUsername(String username)
				throws UsernameNotFoundException {
	        if (username != null && !username.equals("")) {
	            Users user = userDao.getUserByName(username);
	            if (user == null) {
	            	throw new UsernameNotFoundException("UserAccount for name \""
	    					+ username + "\" not found.");
	            }
	            Iterator<Role> it = user.getRoles().iterator();
	            List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
	            while (it.hasNext()) {
	            	String authority = it.next().getName();
	            	GrantedAuthority grantedAuth = new UserGrantedAuthority(authority);
	            	grantedAuthorities.add(grantedAuth);
	            }
	            
	            CustomUserDetails cu = new CustomUserDetails(user.getId(), user.getFirstName(), user.getPassword(),
	                                           grantedAuthorities.toArray(new GrantedAuthority[]{}), user.getEnabled());
	            return cu;
	        } else {
	            return null;
	        }

		}

		@Override
		public boolean login(String userName, String password) {
			try {
				Authentication authenticate = authenticationManager
						.authenticate(new UsernamePasswordAuthenticationToken(
								userName, password));
				if (authenticate.isAuthenticated()) {
					SecurityContextHolder.getContext().setAuthentication(
							authenticate);				
					return true;
				}
			} catch (AuthenticationException e) {			
			}
			return false;
		}

	}
